package com.ldk.admin.controller;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.CjtCity;
import com.ldk.framework.entity.CjtRoad;
import com.ldk.framework.entity.Dict;
import com.ldk.framework.service.ICjtCityService;
import com.ldk.framework.service.IDictService;

import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/citcity")
public class CjtCityController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "citcity";
    /**
     * 模块名称
     */
    private final String module = "开通城市";

    @Autowired
    private ICjtCityService cjtCityService;

    @RequestMapping("/list")
    //public ModelAndView list(ModelMap map){
    public ModelAndView list(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        if (this.getRoleId(request) == 6) {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "", "");
        } else {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add");
        }

        map.addAttribute("route", route);
        //操作日志
        //this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
		/*if (this.getRoleId(request) == 6) {
			return new ModelAndView("/cjt/listdict_sj");
		} else {
			return new ModelAndView("/cjt/listdict");
		}*/
        return new ModelAndView("/cjt/citylist");
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LigerUIGridResult<CjtCity> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                              @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                              @RequestParam(value = "city", required = false, defaultValue = "") String city,
                                              HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        CjtCity query = new CjtCity();
        if(!TextUtils.isEmpty(city)){
            query.setCity(city);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<CjtCity> result = cjtCityService.selectPageList("", query, pageable);

        LigerUIGridResult<CjtCity> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();
        return grid;
    }

    @RequestMapping("/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add", "", "");
        setForm(map, "/" + route + "/insert", null);

        CjtRoad model = new CjtRoad();

        return new ModelAndView("/cjt/cityinfo", "model", model);
    }

    @RequestMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        CjtCity query = new CjtCity();
        query.setId(id);

        CjtCity model = cjtCityService.selectByKey("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list");
        }
        setLinks(map, module + "管理", "/" + route + "/list", "编辑" + module, "/" + route + "/edit/" + id, "", "");
        setForm(map, "/" + route + "/update", null);

        return new ModelAndView("/cjt/cityinfo", "model", model);
    }

    @RequestMapping("/insert")
    public ModelAndView insert(@ModelAttribute("model") CjtCity model, RedirectAttributes redAttr, ModelMap map,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try {
            CjtCity query = new CjtCity();
            query.setCity(model.getCity());

            CjtCity exitObject = cjtCityService.selectOne("", query);
            if (exitObject != null) {
                rst.AddError(String.format("%s已经存在", model.getCity()));
                return new ModelAndView("redirect:/" + route + "/add");
            }
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }

            model.setDatetime(SystemUtil.getAllSeconds());

            this.insertOplog(request, module, "", "", "添加:" + model.getCity(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = cjtCityService.insert("", model);
            if (row > 0) {
                rst.AddOk("添加" + module + "成功");
            } else {
                rst.AddError("添加" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("添加" + module + "失败，失败原因：" + e.getMessage());
        }
        return new ModelAndView("redirect:/" + route + "/add");
    }

    @RequestMapping("/update")
    public ModelAndView update(@ModelAttribute("model") CjtCity model, RedirectAttributes redAttr, ModelMap map,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        try {
            CjtCity query = new CjtCity();
            query.setCity(model.getCity());

            CjtCity exitObject = cjtCityService.selectOne("", query);
            if (exitObject != null && exitObject.getId() != model.getId()) {
                rst.AddError(String.format("%s已经存在", model.getCity()));
                return new ModelAndView("redirect:/" + route + "/edit/{id}");
            }

            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }

            this.insertOplog(request, module, "", "", "添加:" + model.getCity(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = cjtCityService.updateByKey("", model);
            if (row > 0) {
                rst.AddOk("修改" + module + "成功");
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败，失败原因：" + e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/edit/{id}");
    }

    @ResponseBody
    @RequestMapping("/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        int row = 0;
        try {
            //操作日志
            CjtCity query = new CjtCity();
            query.setId(id);
            CjtCity dict = cjtCityService.selectByKey("", query);
            this.insertOplog(request, module, "", "", "删除:" + dict.getCity(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            row = cjtCityService.deleteByKey("", query);
        } catch (Exception e) {

        }
        if (row > 0) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }
}
